<template>
  <div id="contractPrintTemp" class="route-page">
    <section class="pl-10 bg-white">
      <a-tabs v-model:activeKey="activeTab">
        <a-tab-pane
          v-for="tab of TABS"
          :key="tab.key"
          :tab="tab.title"
        ></a-tab-pane>
      </a-tabs>
    </section>

    <a-card class="mt-10" size="small" v-if="currentTab.key == 'template'">
      <a-row type="flex" justify="space-between" align="middle">
        <a-tabs v-model:activeKey="printCardTabKey" @change="onPrintTabChange">
          <a-tab-pane
            v-for="item of printCardTabList"
            :key="item.key"
            :tab="item.tab"
          ></a-tab-pane>
        </a-tabs>
        <a-button
          v-permission="['contractPrintList', 'curd', 'add']"
          type="primary"
          @click="add()"
        >
          <template #icon>
            <PlusOutlined />
          </template>
          {{ currentTab.title }}
        </a-button>
      </a-row>
      <!-- 表格 -->
      <a-table
        sticky
        :columns="currentTab.columns"
        :data-source="dataList"
        row-key="id"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        :scroll="{ x: 'max-content' }"
      >
        <template #bodyCell="{ text, record, index, column }">
          <template v-if="column.key === 'action'">
            <a-button
              type="link"
              v-permission="['contractPrintList', 'curd', 'edit']"
              @click="add(record.id)"
            >
              编辑
            </a-button>
            <a-button
              type="link"
              v-permission="['contractPrintList', 'curd', 'delete']"
              danger
              @click="deleteTemplate(record)"
            >
              删除
            </a-button>
          </template>
        </template>
      </a-table>
    </a-card>

    <a-card class="mt-10" :title="currentTab.title" size="small" v-else>
      <template #extra>
        <a-button
          v-permission="['contractPrintList', 'curd', 'add']"
          type="primary"
          @click="add()"
        >
          <template #icon>
            <PlusOutlined />
          </template>
          {{ currentTab.title }}
        </a-button>
      </template>
      <!-- 表格 -->
      <a-table
        sticky
        :columns="currentTab.columns"
        :data-source="dataList"
        row-key="id"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        :scroll="{ x: 'max-content' }"
      >
        <template #bodyCell="{ text, record, index, column }">
          <!-- 操作 -->
          <template v-if="column.key === 'action'">
            <a-button
              type="link"
              v-permission="['contractPrintList', 'curd', 'edit']"
              @click="add(record.id)"
            >
              编辑
            </a-button>
            <a-button
              type="link"
              v-permission="['contractPrintList', 'curd', 'delete']"
              danger
              @click="deleteTemplate(record)"
            >
              删除
            </a-button>
          </template>
        </template>
      </a-table>
    </a-card>

    <add-template
      :visible="addVisible"
      :tabList="addTabList"
      :title="addTitle"
      :id="templateId"
      pageForm="print"
      @onCancel="handleAddCancel"
      @success="handleAddSuccess"
    />
    <add-watermark
      :visible="markVisible"
      :id="markId"
      @cancel="handleMarkCancel"
      @success="handleMarkSuccess"
    />
  </div>
</template>

<script>
import { defineComponent, ref, watch, computed } from "vue";
import { PlusOutlined } from "@ant-design/icons-vue";
import AddTemplate from "../RetreatAgreement/modules/AddTemplate.vue";
import addWatermark from "./modules/AddWatermark.vue";
import request from "../../../common/utils/request";
import utils from "../../../common/utils/utils";
import { message } from "ant-design-vue";

export default defineComponent({
  name: "contractPrintList",
  components: { PlusOutlined, AddTemplate, addWatermark },
  setup() {
    /**
     * @description: 标签栏
     */
    const activeTab = ref(TABS[0].key);
    const currentTab = ref(TABS[0]);
    watch(activeTab, (val) => {
      currentTab.value = TABS.find((item) => item.key === val);
      page.value = 1;
      getTableData();
    });

    /**
     * @description: 分页信息
     */
    const page = ref(1);
    const pageSize = ref(10);
    const total = ref(0);
    const pagination = computed(() => ({
      total: total.value,
      current: page.value,
      pageSize: pageSize.value,
      showSizeChanger: true,
    }));
    const handleTableChange = (pager, filters, sorter) => {
      page.value = pager.current;
      pageSize.value = pager.pageSize;
    };

    const printCardTabKey = ref("normal");

    const onPrintTabChange = (key) => {
      printCardTabKey.value = key;
      page.value = 1;
      getTableData();
    };

    /**
     * @description: 表格数据
     */
    const loading = ref(false);
    const dataList = ref([]);
    watch([page, pageSize], () => {
      getTableData();
    });
    const getTableData = () => {
      loading.value = true;
      let params = { page: page.value, limit: pageSize.value };
      if (currentTab.value.key == "template") {
        params.scene = printCardTabKey.value;
      }
      request
        .get("/org", currentTab.value.action, {
          ...params,
        })
        .then((res) => {
          dataList.value = res.list;
          total.value = Number(res.total);
        })
        .finally(() => {
          loading.value = false;
        });
    };

    /**
     * @description: 增删改操作
     */
    const add = (id) => {
      if (activeTab.value == "template") {
        addTemplate(id);
        return;
      }
      if (activeTab.value == "watermark") {
        addWatermark(id);
        return;
      }
    };
    // 合同模板
    const addVisible = ref(false);
    const addTitle = ref("合同打印模版");
    const addTabList = ref(PRINT_TABS);
    const templateId = ref(0);
    const addTemplate = (id) => {
      templateId.value = id || 0;
      addVisible.value = true;
    };
    const handleAddCancel = () => {
      addVisible.value = false;
    };
    const handleAddSuccess = () => {
      handleAddCancel();
      page.value = 1;
      getTableData();
    };
    // 水印模板
    const markVisible = ref(false);
    const markId = ref(0);
    const addWatermark = (id) => {
      markId.value = id || 0;
      markVisible.value = true;
    };
    const handleMarkCancel = () => {
      markVisible.value = false;
    };
    const handleMarkSuccess = () => {
      handleMarkCancel();
      page.value = 1;
      getTableData();
    };

    // 删除
    const deleteTemplate = (record) => {
      let content = "";
      let url = "";
      if (activeTab.value == "template") {
        content = `确认删除合同打印模版“${record.template_name}”吗？`;
        url = "/contract/printContractDel";
      } else if (activeTab.value == "watermark") {
        content = `确认删除水印模版“${record.name}”吗？`;
        url = "/contract/watermark";
      }
      utils.modalConfirm({
        content,
        onOk: () => {
          request
            .del("/org", url, {
              id: record.id,
              needMsg: true,
            })
            .then((res) => {
              message.success(res.msg || "删除成功！");
              getTableData();
            });
        },
      });
    };

    // 初始化
    const init = () => {
      getTableData();
    };

    init();

    return {
      TABS,
      dataList,
      activeTab,
      currentTab,
      loading,
      pagination,
      addVisible,
      addTitle,
      addTabList,
      templateId,
      markVisible,
      markId,
      handleAddCancel,
      handleAddSuccess,
      handleMarkCancel,
      handleMarkSuccess,
      add,
      deleteTemplate,
      handleTableChange,

      printCardTabList,
      printCardTabKey,
      onPrintTabChange,
    };
  },
});

const PRINT_TABS = [
  { key: "mainInfo", title: "基本信息", type: "copy" },
  {
    key: "leaseClause",
    title: "租赁费用条款",
    type: "copy",
    remark: [
      "若一份合同存在多个租赁条款，则需通过手动增加数字用于区分。如租赁信息2保证金：代表合同中第二个租赁条款的保证金。",
      "若一个租赁条款内存在多个租期条款，也可按以上方式区分。如租赁信息2租期条款2租金单价：代表合同中第二个租赁条款的第二个租期条款的租金单价。",
    ],
  },
  { key: "propertyClause", title: "物业费用条款", type: "copy" },
  {
    key: "specialClause",
    title: "自定义费用条款",
    type: "copy",
    remark: [
      "若同一份合同内存在多个自定义费用条款，则需通过手动增加数字用于区分。如自定义条款保证金：代表合同中除租赁、物业条款外第一个添加的自定义类型的合同条款的保证金。如自定义条款2面积：代表合同中除租赁、物业条款外第二个添加的自定义类型的合同条款的租赁面积。",
    ],
  },
  { key: "contractDetail", title: "合同明细", type: "copy" },
  { key: "remarkClause", title: "备注条款", type: "copy" },
  { key: "tab2", title: "上传合同打印模板", type: "form" },
];

const tempColumns = [
  {
    title: "模板名称",
    dataIndex: "template_name",
    key: "template_name",
  },
  {
    title: "操作",
    dataIndex: "id",
    key: "action",
  },
];

const markColums = [
  {
    title: "水印名称",
    dataIndex: "name",
    key: "name",
  },
  {
    title: "操作",
    dataIndex: "id",
    key: "action",
  },
];

const TABS = [
  {
    key: "template",
    title: "合同打印模板",
    action: "/contract/contractPrintList",
    columns: tempColumns,
  },
  {
    key: "watermark",
    title: "合同水印",
    action: "/contract/watermarkList",
    columns: markColums,
  },
];

const printCardTabList = [
  {
    key: "normal",
    tab: "正式合同",
  },
  {
    key: "purpose",
    tab: "意向合同",
  },
];
</script>

<style lang="less" scoped>
#contractPrintTemp {
  padding: 10px;
  &:deep(.ant-tabs-bar) {
    margin: 0;
  }
}
</style>
